<template>
    <div>
        <h2>短信验证登录/注册</h2>
        <van-form @failed="onFailed" @submit="onSubmit">
            <van-cell-group inset>
                <!-- 手机号 -->
                <van-field v-model="fromInfo.phone" required name="用户名" label="+86" placeholder="手机号"
                    @update:model-value="Updated" :rules="[{ required: true, message: '手机号必填' },
                    { phonePattern, message: '请输入正确的手机号' }]" />
                <!-- 验证码 -->
                <van-field v-model="fromInfo.sms" required center clearable label="验证码" :rules="[{ required: true, message: '验证码必填' },
                { pattern: /^\d{6}$/, message: '请输入正确的验证码' }]">
                    <template #button>
                        <van-button size="small" :disabled="disabled" @click="djs" type="primary">{{ msg }}</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
    </div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import axios from '@/request'
import { showToast } from 'vant';

const fromInfo = reactive({
    phone: '',
    sms: ''
})
const phonePattern = /^1[3-9]\d{9}$/;
// const onFailed = (errorInfo) => {
//     console.log('failed', errorInfo);
// };

const disabled = ref(true)
const msg = ref('获取验证码')
const Updated = () => {
    if (phonePattern.test(fromInfo.phone)) {
        disabled.value = false
    }
    else {
        disabled.value = true
    }
}
// 校验通过则点击“获取验证码”按钮，此按钮文案变成60s倒计时，每秒减1，到0时变回获取验证码
let time = 5
let timer
const djs = () => {
    timer = setInterval(() => {
        if (time > 0) {
            time--
            msg.value = `${time}s倒计时`
            disabled.value = true
        } else {
            clearInterval(timer)
            msg.value = `获取验证码`
            disabled.value = false
            time = 5
            // 6.点击获取验证码掉接口获取验证码，并回显到验证码输入框
            axios.get('/getyzm').then(res => {
                fromInfo.sms = res.yzm
            })
        }
    }, 1000)
}

// 7.点击登录校验11位数字和6位数字验证码，校验通过调用登录接口（mock实现）获取token和用户信息
// 8.使用本地存储存储用户信息与token

const onSubmit = (values) => {
    axios.post('/api/login').then(res => {
        if (res.code == 1) {
            showToast({
                message: res.data.message,
                type: 'success',
                duration: 1500
            });
        }
        // 8.使用本地存储存储用户信息与token
        localStorage.setItem('token',res.data.token)
        localStorage.setItem('username',res.data.username)
        localStorage.setItem('phone',fromInfo.phone)
        console.log(res.data);
        console.log(JSON.stringify(fromInfo.phone));
    })
};

</script>
<style scoped>
h2 {
    text-align: center;
}
</style>